name: Package

on:
 workflow_dispatch:
  inputs:
   release:
    type:        boolean
    description: 'Release'
    required:    true
    default:     false

defaults:
 run:
  shell: bash

env:
 GHA_SCRIPTS: ".github/workflows/scripts"
 RELEASE_PICS: "Resources/Gallery/releases"

jobs:

 Publish:
  runs-on: windows-latest
  env:
   MOD_DIR:            "Fallout2/Fallout1in2"
   MOD_RELEASE_ZIP:    "Fallout1in2.zip"
  steps:

  - name: Clone
    uses: actions/checkout@v4
    with:
     # required for commits counter
     fetch-depth: 0

  - name: Preparations
    run:  |
          :
          event="${{ github.event_name }}"
          if [ "$event" == "workflow_dispatch" ]; then
             if [ "${{ github.event.inputs.release }}" == "true" ]; then
                event="${event}:release"
             fi
          fi

          pre=
          if   [ "$event" == "workflow_dispatch" ]; then
               pre="--prerelease"
          elif [ "$event" == "workflow_dispatch:release" ]; then
               pre=
          else
               echo "[ERROR] unknown event<$event>"
               exit 1
          fi

          echo MOD_RELEASE_NAME=$($GHA_SCRIPTS/version.sh release) >> $GITHUB_ENV
          echo MOD_RELEASE_TAG=$($GHA_SCRIPTS/version.sh tag) >> $GITHUB_ENV
          echo MOD_RELEASE_DRAFT="--draft" >> $GITHUB_ENV
          echo MOD_RELEASE_PRE=$pre >> $GITHUB_ENV
          echo MOD_RELEASE_BODY=NEWS.md >> $GITHUB_ENV

  - name: Format release text
    run:  |
          :
          # (md)->(nma) copy raw version
          cp "$MOD_RELEASE_BODY" "$MOD_RELEASE_BODY.nma"

          # (nma) insert list head
          sed -ri 's!^(Notable changes .+)!\1\n\n[color=#00b300][b]Changelog[/b][/color]\n[spoiler]\n[list]!' "$MOD_RELEASE_BODY.nma"

          # (nma) replace list elements
          sed -ri 's!^-[\ ]+\*\*([A-Za-z]+)\*\*![*][b]\1[/b]!g' "$MOD_RELEASE_BODY.nma"

          # (nma) append list tail
          echo "" >> "$MOD_RELEASE_BODY.nma"
          echo "[/list]" >> "$MOD_RELEASE_BODY.nma"
          echo "[/spoiler]" >> "$MOD_RELEASE_BODY.nma"
          echo "" >> "$MOD_RELEASE_BODY.nma"

          # (nma) append link
          echo "You can find the latest release [url=https://github.com/rotators/Fo1in2/releases/latest/download/Fallout1in2.zip]here[/url]." >> "$MOD_RELEASE_BODY.nma"

          # (nma) replace header text with image if available, strip otherwise
          if [ -f "$RELEASE_PICS/release_v$($GHA_SCRIPTS/version.sh raw).png" ]; then
             sed -ri "s!^Notable changes .+![img]https://raw.githubusercontent.com/$GITHUB_REPOSITORY/$(echo "$GITHUB_REF" | awk -F / '{print $3}')/$RELEASE_PICS/release_v$(.github/workflows/scripts/version.sh raw).png[/img]!" "$MOD_RELEASE_BODY.nma"
          else
             sed -ri 's!^Notable changes .+!!' "$MOD_RELEASE_BODY.nma"
          fi

          # (md) replace header text with image if available
          if [ -f "$RELEASE_PICS/release_v$($GHA_SCRIPTS/version.sh raw).png" ]; then
             sed -ri "s!^Notable changes .+!<p align=\"center\"><img src=\"https://raw.githubusercontent.com/$GITHUB_REPOSITORY/$(echo "$GITHUB_REF" | awk -F / '{print $3}')/$RELEASE_PICS/release_v$($GHA_SCRIPTS/version.sh raw).png\" alt=\"$($GHA_SCRIPTS/version.sh tag)\"/></p>\\n!" "$MOD_RELEASE_BODY"
          fi

          # (nma)+>(md) merge formatting
          echo "" >> "$MOD_RELEASE_BODY"
          echo "---" >> "$MOD_RELEASE_BODY"
          echo "" >> "$MOD_RELEASE_BODY"
          echo '```' >> "$MOD_RELEASE_BODY"
          cat "$MOD_RELEASE_BODY.nma" >> "$MOD_RELEASE_BODY"
          echo '```' >> "$MOD_RELEASE_BODY"

  - name: Update version info
    run:  |
          :
          $GHA_SCRIPTS/ddraw.sh set-dll-version --ini=$MOD_DIR/ddraw.ini --dll=$MOD_DIR/ddraw.dll
          $GHA_SCRIPTS/ddraw.sh set --ini=$MOD_DIR/ddraw.ini --cfg=Misc --key=VersionString --val="$($GHA_SCRIPTS/version.sh game)"

  - name: Cleanup
    run:  |
          :
          rm -f  $MOD_DIR/ddraw.*.ini
          rm -f  $MOD_DIR/mods/fo1_base/sound/sfx/regsnd.exe
          find $MOD_DIR -name '.gitignore' -delete
          find $MOD_DIR -name '.gitattributes' -delete
          find $MOD_DIR -iname '.nopack' -or -iname '.nopackage' | while read file; do
               dir="$(dirname "$file")"
               if [[ -d "$dir" ]]; then
                  rm -fr "$dir/"
               fi
          done
          # always last
          find $MOD_DIR -type d -empty -delete


  - name: Copy UndatUI
    run:  |
          :
          cp "Tools/UndatUI/undat.exe" $MOD_DIR
          cp "Tools/UndatUI/undat_files.txt" $MOD_DIR

  - name: Copy UndatCLI
    run:  |
          :
          cp "Tools/UndatCLI/undat.sh" $MOD_DIR
          cp "Tools/Fallout2_ProtoManager/dat2.exe" $MOD_DIR
          # what's going on here
          dos2unix "$MOD_DIR/undat.sh"

  - name: Disable debug options
    run:  |
          :
          $GHA_SCRIPTS/ddraw.sh set --ini=$MOD_DIR/ddraw.ini --cfg=Debugging --key=Enable --val=0
          $GHA_SCRIPTS/ddraw.sh set --ini=$MOD_DIR/ddraw.ini --cfg=Debugging --key=DebugMode --val=0
          $GHA_SCRIPTS/ddraw.sh set --ini=$MOD_DIR/ddraw.ini --cfg=Debugging --key=ConsoleWindow --val=0
          $GHA_SCRIPTS/ddraw.sh set --ini=$MOD_DIR/config/fo1_settings.ini --cfg=DEBUG --key=GVAR_ENABLE_DEBUG_MENU --val=0
          $GHA_SCRIPTS/ddraw.sh set --ini=$MOD_DIR/config/fo1_settings.ini --cfg=DEBUG --key=GVAR_ENABLE_DEBUG_MESSAGES --val=0

          $GHA_SCRIPTS/ddraw.sh list --ini=$MOD_DIR/ddraw.ini --cfg=Debugging --section-name
          $GHA_SCRIPTS/ddraw.sh list --ini=$MOD_DIR/config/fo1_settings.ini --cfg=DEBUG --section-name

  - name: Format documentation
    run:  |
          :
          for md in $(find $MOD_DIR -type f -name '*.[Mm][Dd]' | sort); do
              txt="$(echo "$md" | sed -e 's!\.[Mm][Dd]$!\.txt!')"

              dos2unix "$md"

              # replace "[path](path)" (must be exactly the same) with "path"
              sed -ri 's!\[([A-Za-z0-9\.\_\/\\\-]+)\]\(\1\)!\1!g' "$md"

              # replace "[text](url)" with "text: url"
              sed -ri 's!\[(.+?)\]\((.+?)\)!\1: \2!g' "$md"

              # remove lines with "```" or "```blabla" only
              sed -ri '/^[\t\ ]*[\`]+[a-z]?[\t\ ]*$/d' "$md"

              # remove lines which looks like html
              sed -ri '/^<.+>$/d' "$md"

              # remove first line if blank
              sed -ri '1{/^$/d}' "$md"

              # wrap long lines to fit into default notepad.exe window size
              fold -w 100 -s "$md" > "$txt"

              unix2dos "$md" "$txt"
              echo ::group::$md
              git diff "$md" || true
              echo ::endgroup::
              rm "$md"

              echo ::group::$txt
              cat "$txt" 2>&1
              echo ::endgroup::
          done

  - name: Pack
    run:  7z a "${GITHUB_WORKSPACE}/${MOD_RELEASE_ZIP}" -m5=Deflate Fallout1in2
    working-directory: Fallout2

  - name: Create release
    run: gh release create $MOD_RELEASE_TAG --title "$MOD_RELEASE_NAME" $MOD_RELEASE_PRE $MOD_RELEASE_DRAFT --notes-file "$MOD_RELEASE_BODY"
    env:
     GH_TOKEN: ${{ secrets.ANTALASKAYA_TOKEN }}

  - name: Upload main package
    run:  gh release upload $MOD_RELEASE_TAG "$MOD_RELEASE_ZIP"
    env:
     GH_TOKEN: ${{ secrets.ANTALASKAYA_TOKEN }}

  - name: Show release
    run:  gh release view $MOD_RELEASE_TAG --json url --jq '.url'; gh release view $MOD_RELEASE_TAG --json assets --jq ".assets[0].url"
    env:
     GH_TOKEN: ${{ secrets.ANTALASKAYA_TOKEN }}
